/*******************************************************************************
 * Copyright 2011 WaTho
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package de.wathoserver.android.dragoid.activity.singlebuilding;

import java.util.ArrayList;

import android.app.Dialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.gesture.Gesture;
import android.gesture.GestureLibraries;
import android.gesture.GestureLibrary;
import android.gesture.GestureOverlayView;
import android.gesture.GestureOverlayView.OnGesturePerformedListener;
import android.gesture.Prediction;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import de.wathoserver.android.dragoid.R;
import de.wathoserver.android.dragoid.api.Building;
import de.wathoserver.android.dragoid.api.DragoApi;
import de.wathoserver.android.dragoid.api.DragoStore;
import de.wathoserver.android.dragoid.api.DragoidConstants;
import de.wathoserver.android.dragoid.util.DialogHelper;
import de.wathoserver.android.dragoid.util.UrlParsingActivity;

/**
 * Zeigt ein Gebaude an. Dient als Container für die Tabs.
 * 
 * @author watho
 * 
 */
public class SingleBuildingActivity extends TabActivity implements
		DragoidConstants {
	private static final String SELECTED_TAB = "singlebuilding_selectedtab";
	public static final String TAB_INFO = "singlebuilding_tab_info";
	public static final String TAB_MATERIAL = "singlebuilding_tab_material";
	public static final String TAB_UPGRADE = "singlebuilding_tab_upgrade";
	private GestureLibrary library;
	private int pos;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.singlebuilding);
		// Initialisiere Gestensteuerung
		library = GestureLibraries.fromRawResource(this, R.raw.gestures);
		if (!library.load()) {
			Log.e(LOG_TAG, "Gesten konnten nicht geladen werden.");
		} else {
			if (library != null) {
				GestureOverlayView gestures = (GestureOverlayView) findViewById(R.id.gestures);
				gestures.addOnGesturePerformedListener(new OnGesturePerformedListener() {

					@Override
					public void onGesturePerformed(GestureOverlayView overlay,
							Gesture gesture) {
						ArrayList<Prediction> predictions = library
								.recognize(gesture);

						// We want at least one prediction
						if (predictions.size() > 0) {
							Prediction prediction = predictions.get(0);
							// We want at least some confidence in the result
							if (prediction.score > 1.0) {
								String action = predictions.get(0).name;
								int newPos = -1;
								if ("next".equals(action)) {
									newPos = DragoStore.getDragoStore()
											.getNextBuilding(pos);
								} else if ("previous".equals(action)) {
									newPos = DragoStore.getDragoStore()
											.getPreviousBuilding(pos);
								}
								if (newPos != -1) {
									startActivity(createIntent(
											SingleBuildingActivity.this,
											newPos, getTabHost()
													.getCurrentTabTag()));
								}
							}
						}
					}
				});
			}
		}

		Resources res = getResources();
		Intent parentIntent = getIntent();
		pos = parentIntent.getIntExtra(Building.COL_POSITION, -1);
		showDialog(UrlParsingActivity.DIALOG_PROGRESS);
		try {
			DragoApi.getApi().updateSingleBuilding(pos);
			DragoStore.getDragoStore().getUserInfo().updateUI(this);
		} catch (IllegalAccessException e) {
			Log.e(LOG_TAG, "Gebäude konnte nicht aktualisiert werden.", e);
		}
		dismissDialog(UrlParsingActivity.DIALOG_PROGRESS);
		String tabToSelect = parentIntent.getStringExtra(SELECTED_TAB);
		Building b = DragoStore.getDragoStore().getBuildings().get(pos);
		((TextView) findViewById(R.id.building_name)).setText(b.getName());
		TabHost tabHost = getTabHost();
		TabHost.TabSpec spec;
		Intent intent;

		// Create an Intent to launch an Activity for the tab (to be reused)
		intent = new Intent().setClass(this, SingleBuildingInfoActivity.class);
		intent.putExtra(Building.COL_POSITION, pos);
		// Initialize a TabSpec for each tab and add it to the TabHost
		spec = tabHost.newTabSpec(TAB_INFO)
				.setIndicator(res.getText(R.string.singlebuilding_info))
				.setContent(intent);
		tabHost.addTab(spec);

		if (b.getMaterial().size() > 0) {
			intent = new Intent().setClass(this,
					SingleBuildingRessourcesActivity.class);
			intent.putExtra(Building.COL_POSITION, pos);
			spec = tabHost.newTabSpec(TAB_MATERIAL)
					.setIndicator(res.getText(R.string.singlebuilding_res))
					.setContent(intent);
			tabHost.addTab(spec);
		}

		intent = new Intent().setClass(this,
				SingleBuildingUpgradeActivity.class);
		intent.putExtra(Building.COL_POSITION, pos);
		spec = tabHost.newTabSpec(TAB_UPGRADE)
				.setIndicator(res.getText(R.string.singlebuilding_upgrade))
				.setContent(intent);
		tabHost.addTab(spec);

		tabHost.setCurrentTabByTag(tabToSelect);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.singlebuildingsmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.singlebuildings_destroy:
			// intent = new Intent().setClass(this, AccountActivity.class);
			// startActivity(intent);
			Toast toast = Toast.makeText(this, "Geht noch nicht",
					Toast.LENGTH_SHORT);
			toast.show();
			return true;
		case R.id.singlebuildings_stop:
			Toast toast2 = Toast.makeText(this, "Geht noch nicht",
					Toast.LENGTH_SHORT);
			toast2.show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Erzeugt einen Intent zum starten dieser Aktivität mit dem entsprechendem
	 * Gebäude und dem Tab .
	 * 
	 * @param pos
	 * @param tabTag
	 * @return
	 */
	public static Intent createIntent(Context context, int pos, String tabTag) {
		Intent intent = new Intent(context, SingleBuildingActivity.class);
		intent.putExtra(Building.COL_POSITION, pos);
		intent.putExtra(SELECTED_TAB, tabTag);
		return intent;
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		return DialogHelper.createDialogById(this,
				UrlParsingActivity.DIALOG_PROGRESS);
	}
}
